package com.matt.sooncleaner.web

import android.app.Activity
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.webkit.WebChromeClient
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import com.blankj.utilcode.util.LogUtils

class WebViewUtils(
    webView: WebView,
    url: String?,
    val webViewInterface: WebViewInterface?,
    val isHtml: Boolean? = false,
) {

    interface WebViewInterface {
        fun onReceivedTitle(title: String?, isForce: Boolean = false)
        fun finishActivity()
    }

    init {
        (webView.context as? Activity)?.window?.setFormat(PixelFormat.TRANSLUCENT)
        webView.settings.javaScriptEnabled = true // 可用JS

        webView.settings.builtInZoomControls = true
        webView.settings.loadWithOverviewMode = true
        webView.settings.useWideViewPort = true
        webView.settings.setSupportZoom(true)
        webView.settings.allowFileAccess = true
        try {
            webView.settings.domStorageEnabled = true
        } catch (e: Exception) {
            e.printStackTrace()
        }
        webView.settings.displayZoomControls = false
        webView.settings.textZoom = 100

        webView.settings.mediaPlaybackRequiresUserGesture = false
        webView.settings.defaultTextEncodingName = "utf-8"
        webView.settings.javaScriptCanOpenWindowsAutomatically = false
        webView.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(p0: WebView?, p1: String?) {
                super.onReceivedTitle(p0, p1)
                webViewInterface?.onReceivedTitle(p1)
            }
        }
        webView.webViewClient = object : WebViewClient() {
            override fun onPageStarted(p0: WebView?, p1: String?, p2: Bitmap?) {
                super.onPageStarted(p0, p1, p2)
            }

            override fun onPageFinished(p0: WebView?, p1: String?) {
                super.onPageFinished(p0, p1)
            }

            override fun onReceivedError(
                p0: WebView?,
                p1: WebResourceRequest?,
                p2: WebResourceError?,
            ) {
                super.onReceivedError(p0, p1, p2)
            }

            override fun shouldOverrideUrlLoading(webView: WebView?, url: String?): Boolean {
                return super.shouldOverrideUrlLoading(webView, url)
            }
        }
        LogUtils.d("webView_url :$url")
        if (!url.isNullOrEmpty()) {
            webView.loadUrl(url)
        } else if (isHtml == true && !url.isNullOrEmpty()) {
            webView.loadDataWithBaseURL(null, url, "text/html", "utf-8", null)
        }
    }
}